package com.ruoyi.collect.position.manager;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.collect.position.model.CollectorPositionDto;
import com.ruoyi.collect.position.model.FileDto;
import com.ruoyi.collect.position.service.CollectParser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnowflakeIdUtils;
import com.ruoyi.control.domain.JzssHistory;
import com.ruoyi.control.domain.RyssHistory;
import com.ruoyi.position.domain.*;
import com.ruoyi.position.mapper.RycsMapper;
import com.ruoyi.position.mapper.RycyMapper;
import com.ruoyi.position.mapper.RyqjMapper;
import com.ruoyi.position.mapper.RyxzMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
public class PositionParser extends CollectParser {

    public PositionParser(CollectorPositionDto mapperDto, final Charset charset) {
        mapper = mapperDto;
        this.charset = charset;
    }

    @Override
    public void parse(final List<FileDto> files) {
        Stream.of((Consumer<List<FileDto>>) this::analyzeRyqyFile,
                this::analyzeRyjzFile,
                this::analyzeRyxxFile,
                this::anslyzeRyssFile,
                this::anslyzeRycsFile,
                this::anslyzeRycyFile,
                this::anslyzeRyxzFile,
                this::anslyzeRyqjFile,
                this::anslyzeJzssFile
        ).parallel().forEach(a -> tryAnalyze(a, files));

    }

    protected void anslyzeJzssFile(List<FileDto> fileInfos) {
        analyze("JZSS",fileInfos,this::analyzeJzss);
    }

    private void analyzeJzss(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 3) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String positionSubstationCode = getDatum(data, 0);
                    String substationWorkStatus = getWorkStatus(getDatum(data, 1));
                    String substationPowerStatus = getPowerStatus(getDatum(data, 2));
                    String dataTime = getDatum(data, 3);
                    Jzss jzss = new Jzss();
                    jzss.setPositionSubstationCode(positionSubstationCode);
                    jzss.setSubstationWorkStatus(substationWorkStatus);
                    jzss.setSubstationPowerStatus(substationPowerStatus);
                    jzss.setDataTime(sdf.parse(dataTime));
                    Jzss jzssDb = mapper.getJzssService().selectJzssByPersonSubstatonCode(positionSubstationCode);
                    if (jzssDb != null){
                        jzss.setPersonSubstatonId(jzssDb.getPersonSubstatonId());
                        mapper.getJzssService().updateJzss(jzss);
                    }else {
                        jzss.setPersonSubstatonId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getJzssService().insertJzss(jzss);
                    }
                    JzssHistory jzssHistory = new JzssHistory();
                    BeanUtils.copyProperties(jzss,jzssHistory);
                    jzssHistory.setUpdateTime(new Date());
                    jzssHistory.setPersonSubstatonId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    mapper.getJzssHistoryService().insertJzssHistory(jzssHistory);
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    protected void anslyzeRyqjFile(List<FileDto> fileInfos) {
        analyze("RYQJ",fileInfos,this::analyzeRyqj);
    }

    private void analyzeRyqj(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 9) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String positionPersonCode = getDatum(data, 0);
                    String personName = getDatum(data, 1);
                    String alarmStartTime = getDatum(data, 2);
                    String alarmEndTime = getDatum(data, 3);
                    String inMineTime = getDatum(data, 4);
                    String positionAreaCode = getDatum(data, 5);
                    String inAreaTime = getDatum(data, 6);
                    String positionSubstationCode = getDatum(data, 7);
                    String inSubstationTime = getDatum(data, 8);

                    Ryqj ryqj = new Ryqj();
                    ryqj.setPersonHelpId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    ryqj.setPositionPersonCode(positionPersonCode);
                    ryqj.setPersonName(personName);
                    ryqj.setInMineTime(sdf.parse(inMineTime));
                    ryqj.setHelpStartTime(sdf.parse(alarmStartTime));
                    if (!"".equals(alarmEndTime)){
                        ryqj.setHelpEndTime(sdf.parse(alarmEndTime));
                    }
                    ryqj.setPositionAreaCode(positionAreaCode);
                    ryqj.setInAreaTime(sdf.parse(inAreaTime));
                    ryqj.setPositionSubstationCode(positionSubstationCode);
                    ryqj.setInSubstationTime(sdf.parse(inSubstationTime));

                    ryqj.setDataTime(DateUtils.getNowDate());
                    List<Ryqj> ryqjList = mapper.getRyqjService().selectRyqjList(ryqj);
                    if (ryqjList != null){
                        for (Ryqj ryqj1 : ryqjList) {
                            ryqj.setPersonHelpId(ryqj1.getPersonHelpId());
                            mapper.getRyqjService().updateRyqj(ryqj);
                        }
                    }else {
                        mapper.getRyqjService().insertRyqj(ryqj);
                    }
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    protected void anslyzeRyxzFile(List<FileDto> fileInfos) {
        analyze("RYXZ",fileInfos,this::analyzeRyxz);
    }

    private void analyzeRyxz(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 9) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String positionPersonCode = getDatum(data, 0);
                    String personName = getDatum(data, 1);
                    String alarmStartTime = getDatum(data, 2);
                    String alarmEndTime = getDatum(data, 3);
                    String inMineTime = getDatum(data, 4);
                    String positionAreaCode = getDatum(data, 5);
                    String inAreaTime = getDatum(data, 6);
                    String positionSubstationCode = getDatum(data, 7);
                    String inSubstationTime = getDatum(data, 8);

                    Ryxz ryxz = new Ryxz();
                    ryxz.setPersonConfineId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    ryxz.setPositionPersonCode(positionPersonCode);
                    ryxz.setPersonName(personName);
                    ryxz.setInMineTime(sdf.parse(inMineTime));
                    ryxz.setAlarmStartTime(sdf.parse(alarmStartTime));
                    if (!"".equals(alarmEndTime)){
                        ryxz.setAlarmEndTime(sdf.parse(alarmEndTime));
                    }
                    ryxz.setPositionAreaCode(positionAreaCode);
                    ryxz.setInAreaTime(sdf.parse(inAreaTime));
                    ryxz.setPositionSubstationCode(positionSubstationCode);
                    ryxz.setInSubstationTime(sdf.parse(inSubstationTime));

                    ryxz.setDataTime(DateUtils.getNowDate());

                    List<Ryxz> ryxzList = mapper.getRyxzService().selectRyxzList(ryxz);
                    if (ryxzList != null){
                        for (Ryxz rycs1 : ryxzList) {
                            ryxz.setPersonConfineId(rycs1.getPersonConfineId());
                            mapper.getRyxzService().updateRyxz(ryxz);
                        }
                    }else {
                        mapper.getRyxzService().insertRyxz(ryxz);
                    }
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    private void anslyzeRycyFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.position.model.FileDto>>) this::analyzeRycy).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeRycy(List<FileDto> fileInfos) {
        analyze("RYCY",fileInfos,this::analyzeRycy);
    }

    private void analyzeRycy(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 8) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String overmanType = getDatum(data, 0);
                    String fixedNumber = getDatum(data, 1);
                    String currentNumber = getDatum(data, 2);
                    String positionAreaCode = getDatum(data, 3);
                    String positionAreaName = getDatum(data, 4);
                    String alarmStartTime = getDatum(data, 5);
                    String alarmEndTime = getDatum(data, 6);
                    String areaPerson = getDatum(data, 7);

                    Rycy rycy = new Rycy();
                    rycy.setPersonOvermanId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    rycy.setOvermanType(overmanType);
                    rycy.setFixedNumber(Long.valueOf(fixedNumber));
                    rycy.setCurrentNumber(Long.valueOf(currentNumber));
                    rycy.setPositionAreaCode(positionAreaCode);
                    rycy.setPositionAreaName(positionAreaName);
                    rycy.setAlarmStartTime(sdf.parse(alarmStartTime));
                    rycy.setAreaPerson(areaPerson);
                    List<Rycy> rycyList = mapper.getRycyService().selectRycyList(rycy);
                    rycy.setDataTime(DateUtils.getNowDate());
                    if (rycyList != null){
                        for (Rycy rycy1 : rycyList) {
                            rycy.setPersonOvermanId(rycy1.getPersonOvermanId());
                            mapper.getRycyService().updateRycy(rycy);
                        }
                    }else {
                        mapper.getRycyService().insertRycy(rycy);
                    }
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    private void anslyzeRycsFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.position.model.FileDto>>) this::analyzeRycs).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeRycs(List<FileDto> fileInfos) {
        analyze("RYCS",fileInfos,this::analyzeRycs);
    }

    private void analyzeRycs(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 9) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String positionPersonCode = getDatum(data, 0);
                    String personName = getDatum(data, 1);
                    String inMineTime = getDatum(data, 2);
                    String alarmStartTime = getDatum(data, 3);
                    String alarmEndTime = getDatum(data, 4);
                    String positionAreaCode = getDatum(data, 5);
                    String inAreaTime = getDatum(data, 6);
                    String positionSubstationCode = getDatum(data, 7);
                    String inSubstationTime = getDatum(data, 8);

                    Rycs rycs = new Rycs();
                    rycs.setPositionPersonCode(positionPersonCode);
                    rycs.setPersonName(personName);
                    rycs.setInMineTime(sdf.parse(inMineTime));
                    rycs.setAlarmStartTime(sdf.parse(alarmStartTime));
                    if (!"".equals(alarmEndTime)){
                        rycs.setAlarmEndTime(sdf.parse(alarmEndTime));
                    }
                    rycs.setPositionAreaCode(positionAreaCode);
                    rycs.setInAreaTime(sdf.parse(inAreaTime));
                    rycs.setPositionSubstationCode(positionSubstationCode);
                    rycs.setInSubstationTime(sdf.parse(inSubstationTime));

                    rycs.setDataTime(DateUtils.getNowDate());
                    List<Rycs> rycsList = mapper.getRycsService().selectRycsList(rycs);
                    if (rycsList != null){
                        for (Rycs rycs1 : rycsList) {
                            rycs.setPersonOvertimeId(rycs1.getPersonOvertimeId());
                            mapper.getRycsService().updateRycs(rycs);
                        }
                    }else {
                        rycs.setPersonOvertimeId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getRycsService().insertRycs(rycs);
                    }
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    private void anslyzeRyssFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.position.model.FileDto>>) this::analyzeRyss).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeRyss(List<FileDto> fileInfos) {
        analyze("RYSS",fileInfos,this::analyzeRyss);
    }

    private void analyzeRyss(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 15) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String positionPersonCode = getDatum(data, 0);
                    String personName = getDatum(data, 1);
                    String inoutFlag = getDatum(data, 2);
                    String inMineTime = getDatum(data, 3);

                    String outMineTime = getDatum(data, 4);
                    String positionAreaCode = getDatum(data, 5);
                    String inAreaTime = getDatum(data, 6);
                    String positionSubstationCode = getDatum(data, 7);
                    String inSubstationTime = getDatum(data, 8);
                    String organizationMode = getDatum(data, 9);
                    String distanceSubstation = getDatum(data, 10);
                    String personStatus = getDatum(data, 11);
                    String isLeader = getWhether(getDatum(data, 12));
                    String isSpecialPerson = getWhether(getDatum(data, 13));
                    String substationTimeMap = getDatum(data, 14);

                    Ryss ryss = new Ryss();
                    ryss.setPositionPersonCode(positionPersonCode);
                    ryss.setPersonName(personName);
                    ryss.setInoutFlag(inoutFlag);
                    if ("2".equals(inoutFlag)){
                        ryss.setOutMineTime(sdf.parse(outMineTime));
                    }
                    ryss.setInMineTime(sdf.parse(inMineTime));
                    ryss.setPositionAreaCode(positionAreaCode);
                    if ("1".equals(inoutFlag)){
                        ryss.setInAreaTime(sdf.parse(inAreaTime));
                    }
                    ryss.setPositionSubstationCode(positionSubstationCode);
                    ryss.setInSubstationTime(sdf.parse(inSubstationTime));
                    if (!"".equals(organizationMode)){
                        ryss.setOrganizationMode(organizationMode);
                    }
                    if (!"".equals(distanceSubstation)){
                        ryss.setDistanceSubstation(Double.valueOf(distanceSubstation));
                    }
                    ryss.setPersonStatus(personStatus);
                    ryss.setIsLeader(isLeader);
                    ryss.setIsSpecialPerson(isSpecialPerson);
                    ryss.setSubstationTimeMap(substationTimeMap);
                    ryss.setUpdateTime(new Date());
                    Ryss ryssDb = mapper.getRyssService().selectRyssByPositionPersonCode(positionPersonCode);
                    if (ryssDb != null){
                        ryss.setPositionRealtimeId(ryssDb.getPositionRealtimeId());
                        mapper.getRyssService().updateRyss(ryss);
                    }else {
                        ryss.setPositionRealtimeId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getRyssService().insertRyss(ryss);
                    }
                    RyssHistory ryssHistory = new RyssHistory();
                    BeanUtils.copyProperties(ryss,ryssHistory);
                    ryssHistory.setUpdateTime(new Date());
                    ryssHistory.setPositionRealtimeId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    mapper.getRyssHistoryService().insertRyssHistory(ryssHistory);
                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    private void analyzeRyxxFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.position.model.FileDto>>) this::analyzeRyxx).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeRyxx(List<FileDto> fileInfos) {
        analyze("RYXX",fileInfos,this::analyzeRyxx);
    }

    private void analyzeRyxx(List<String> matches, String content, FileDto fileInfo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 9) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String personCode = getDatum(data, 0);
                    String personName = getDatum(data, 1);
                    String personJob = getDatum(data, 2);
                    String personRank = getDatum(data, 3);

                    String personTeam = getDatum(data, 4);
                    String birthDate = getDatum(data, 5);
                    String education = getDatum(data, 6);

                    String isLeader = getWhether(getDatum(data, 7));
                    String isSpecialPerson = getWhether(getDatum(data, 8));

                    Ryxx ryxx = new Ryxx();
                    ryxx.setPersonCode(personCode);
                    ryxx.setPersonName(personName);
                    ryxx.setPersonJob(personJob);
                    ryxx.setPersonRank(personRank);
                    if (!"".equals(personTeam)){
                        ryxx.setPersonTeam(personTeam);
                    }
                    if (!"".equals(birthDate)){
                        ryxx.setBirthDate(simpleDateFormat.parse(birthDate));
                    }
                    if (!"".equals(education)){
                        ryxx.setEducation(education);
                    }
                    ryxx.setIsLeader(isLeader);
                    ryxx.setIsSpecialPerson(isSpecialPerson);
                    Ryxx ryxxDb = mapper.getRyxxService().selectRyxxByPersonName(ryxx.getPersonName());
                    if (ryxxDb != null){
                        ryxx.setPersonId(ryxxDb.getPersonId());
                        ryxx.setDataTime(new Date());
                        mapper.getRyxxService().updateRyxx(ryxx);
                    }else {
                        ryxx.setDataTime(new Date());
                        ryxx.setPersonId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getRyxxService().insertRyxx(ryxx);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    private void analyzeRyjzFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.position.model.FileDto>>) this::analyzeRyjz).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeRyjz(List<FileDto> fileInfos) {
        analyze("RYJZ",fileInfos,this::analyzeRyjz);
    }

    private void analyzeRyjz(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 6) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String baseStationCode = getDatum(data, 0);
                    String baseStationName = getDatum(data, 1);
                    Float coordinateX = Float.valueOf(getDatum(data, 2));
                    Float coordinateY = Float.valueOf(getDatum(data, 3));
                    Float coordinateZ = Float.valueOf(getDatum(data, 4));
                    String locationAnnotation = getDatum(data, 5);
                    Ryjz ryjz = new Ryjz();
                    ryjz.setBaseStationCode(baseStationCode);
                    ryjz.setBaseStationName(baseStationName);
                    ryjz.setCoordinateX(coordinateX);
                    ryjz.setCoordinateY(coordinateY);
                    ryjz.setCoordinateZ(coordinateZ);
                    ryjz.setLocationAnnotation(locationAnnotation);
                    ryjz.setDataTime(new Date());
                    Ryjz ryjzDb = mapper.getRyjzService().selectRyjzByBaseStationCode(ryjz.getBaseStationCode());
                    if (ryjzDb != null){
                        ryjz.setBaseStationId(ryjzDb.getBaseStationId());
                        mapper.getRyjzService().updateRyjz(ryjz);
                    }else {
                        ryjz.setBaseStationId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getRyjzService().insertRyjz(ryjz);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    protected String getFileNameRegex(final String type) {
        return String.join("", "(\\d+)_", type, "_(\\d{14}).txt");
    }

    protected String getDatum(String[] data, int index) {
        if (data == null || data.length <= index) {
            log.warn("null[{}]: {}", data, index);
            return null;
        }
        String datum = data[index];
        if (!StringUtils.hasText(datum)) {
            log.warn("empty[{}]: {}", data, index);
        }
        return datum.trim();
    }

    private String getWhether(final String type) {
        if (type == null) {
            return "";
        }
        switch (type) {
            case "1":
                return "是";
            case "0":
                return "否";
        }
        return "";
    }

    protected BigDecimal getDecimal(String[] data, int index) {
        Logger log = LoggerFactory.getLogger(this.getClass());
        if (data == null || data.length <= index || data[index] == null) {
            log.warn("Invalid data or index: data = {}, index = {}", data, index);
            return null;
        }

        String datum = data[index].trim();
        if (!StringUtils.hasText(datum)) {
            log.warn("Empty value at index {}: data = {}", index, data);
            return null;
        }

        try {
            // 将字符串转换为 Decimal
            BigDecimal value = new BigDecimal(datum);
            return value;
        } catch (NumberFormatException e) {
            log.warn("Failed to convert value at index {}: data = {}", index, data, e);
            return null;
        }
    }

    private String getWorkStatus(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "0":
                return "通讯正常";
            case "1":
                return "通讯中断";
            case "2":
                return "故障";
            case "9":
                return "未知";
        }
        return "";
    }

    private String getPowerStatus(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "0":
                return "直流供电";
            case "1":
                return "交流供电";
            case "2":
                return "电源故障";
            case "9":
                return "未知";
        }
        return "";
    }

    private void analyzeRyqyFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<com.ruoyi.collect.position.model.FileDto>>) this::analyzeRyqy).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeRyqy(List<FileDto> fileInfos) {
        analyze("RYQY",fileInfos,this::analyzeRyqy);
    }

    private void analyzeRyqy(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第一个部分处理
                    String[] mines = parts[0].split(";");
                    String mineCode = getDatum(mines, 0);
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 4) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();
                    String positionAreaCode = getDatum(data, 0);
                    String areaType = getDatum(data, 1);
                    Long verifiedPersonNumber = Long.valueOf(getDatum(data, 2));
                    String areaName = getDatum(data, 3);

                    Ryqy ryqy = new Ryqy();
                    ryqy.setPositionAreaCode(positionAreaCode);
                    ryqy.setAreaType(areaType);
                    ryqy.setVerifiedPersonNumber(verifiedPersonNumber);
                    ryqy.setAreaName(areaName);
                    ryqy.setDataTime(new Date());
                    Ryqy ryqyDb = mapper.getRyqyService().selectRyqyByPositionAreaCode(ryqy.getPositionAreaCode());
                    if (ryqyDb != null){
                        ryqy.setPositionAreaId(ryqyDb.getPositionAreaId());
                        mapper.getRyqyService().updateRyqy(ryqy);
                    }else {
                        ryqy.setPositionAreaId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getRyqyService().insertRyqy(ryqy);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }
    
}
